package com.ccteam.fluidmusic.ui.nowplaying

import android.content.res.ColorStateList
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentLyricsPlayerBinding
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.view.bean.LyricsBodyItem
import com.ccteam.fluidmusic.view.bean.NowPlayingMediaData
import com.ccteam.fluidmusic.widget.LyricsRecyclerView
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class LyricsPlayerFragment : Fragment() {

    private var _binding: FragmentLyricsPlayerBinding? = null
    private val binding get() = _binding!!

    /**
     * 因为此Fragment在ViewPager中，需要使用parentFragment的生命周期共享这个ViewModel
     */
    private val nowPlayingViewModel by viewModels<NowPlayingViewModel>(ownerProducer = { parentFragment ?: this})

    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    companion object {

        @JvmStatic
        fun newInstance(): LyricsPlayerFragment {
            return LyricsPlayerFragment()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLyricsPlayerBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // 给歌词View设置LifeCycle，使其能够在正确时机取消监听，暂停滚动等内容
        binding.rvLyrics.setLifecycleOwner(this)
        binding.rvLyrics.setLyricsAdapter(callback)

        nowPlayingViewModel.lyricsConfig.observe(viewLifecycleOwner, {
            binding.rvLyrics.setConfig(it)
        })

        mainActivityViewModel.nowPlayingMediaData.observe(viewLifecycleOwner, {
            it?.let {
                updateMusicInfo(it)
                nowPlayingViewModel.loadLyrics(it)
            } ?: return@observe
        })

        nowPlayingViewModel.lyricsLoading.observe(viewLifecycleOwner, {
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
        })

        nowPlayingViewModel.lyricsList.observe(viewLifecycleOwner, {
            binding.rvLyrics.submitLyricsList(it.second,it.third)
        })

        nowPlayingViewModel.playbackStateLiveData.observe(viewLifecycleOwner, {
            viewLifecycleOwner.lifecycleScope.launch {
                binding.rvLyrics.updateState(it)
            }
        })

        /**
         * 监听对应流动颜色，做好歌词颜色填充
         */
        nowPlayingViewModel.fluidColor.observe(viewLifecycleOwner, {
            if(it == null){
                return@observe
            }
            binding.rvLyrics.updateTextColor(it.second,it.first)
            updateFluidUI(it)
        })

        mainActivityViewModel.mediaAlbumArt.observe(viewLifecycleOwner, {
            updateAlbumArt(it)
        })

        mainActivityViewModel.mediaButtonRes.observe(viewLifecycleOwner, { res ->
            binding.btnPausePlay.setIconResource(res)
        })

        binding.statusView.setRetryClickListener { _ ->
            mainActivityViewModel.nowPlayingMediaData.value?.let {
                nowPlayingViewModel.loadLyrics(it)
            }
        }

        binding.btnPausePlay.setOnClickListener {
            mainActivityViewModel.playOrPause()
        }
    }

    private val callback = object: LyricsRecyclerView.LyricsItemClickCallback{
        override fun lyricsItemClick(lyricsItem: LyricsBodyItem) {
            mainActivityViewModel.seekTo(lyricsItem.startTime,true)
        }
    }

    private fun updateMusicInfo(mediaData: NowPlayingMediaData) = with(binding){
        tvMusicTitle.text = mediaData.title
        tvMusicSubtitle.text = mediaData.artist
    }

    private fun updateAlbumArt(albumArtUri: Pair<Uri?, Uri?>){
        val (_,realParseUri) = albumArtUri
        Glide.with(binding.ivAlbumArt)
            .load(realParseUri)
            .placeholder(R.drawable.img_default_album)
            .into(binding.ivAlbumArt)
    }

    /**
     * 更新灵动UI
     */
    private fun updateFluidUI(colorPair: Pair<Int,Int>) = with(binding){
        val primaryColor = colorPair.first
        btnPausePlay.iconTint = ColorStateList.valueOf(primaryColor)
        tvMusicTitle.setTextColor(primaryColor)
        tvMusicSubtitle.setTextColor(primaryColor)
        statusView.setIconTextTint(primaryColor)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}